<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Response;

/**
 * 示例接口
 */
class Elevator extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*', '*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**  
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */
    // b46979b1e635cbe35fa620f5a1b2d9e1id=1
   public function add()
    {
        $data = $this->request->post();
        $data['posttime']= date('Y-m-d H:i:s',time());
        $data['code'] = md5($data['product_model'] . $data['factory_serial_number'] . $data['factory_date'] . $data['posttime']);
        $code_img_data = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/index/qrcode/index?code=' . $data['code'] . '&type=1';
        $data['code_img_url'] = $this->build($code_img_data);
        $res = Db::name('elevator_basic_info')->insert($data);
        $this->success('添加成功');
         
        // return json_encode($data,JSON_UNESCAPED_UNICODE);
        // $this->success('返回成功', $this->request->param());
    }

    public function list(){
        
        $data = Db::name('elevator_basic_info')->order('id DESC')->select();
        return json_encode($data,JSON_UNESCAPED_UNICODE);
    }

    public function group(){
    $rawData = Db::name('auth_group')->select();
    $formattedData = ['data' => $rawData]; // 将原始数据放入'data'键下
    header('Content-Type: application/json');
    echo json_encode($formattedData, JSON_UNESCAPED_UNICODE);
    exit;
    }

    public function eleqx(){
        $data = Db::name('auth_group')->select();
        return json_encode($data,JSON_UNESCAPED_UNICODE);
    }

    public function findOne(){
        $id = input('post.id');
        $data = Db::name('elevator_basic_info')->find($id);
        return json_encode($data,JSON_UNESCAPED_UNICODE);
    }

    public function type(){
    // 查询type字段
    $data = Db::name('elevator_type')->field('type')->select();

    // 映射转换，只保留type值，形成简单数组
    $type = array_column($data, 'type');

    return json_encode($type, JSON_UNESCAPED_UNICODE);
    }

    public function firm(){
    // 查询type字段
    $firm = Db::name('corporation')->field('name')->select();
    // 映射转换，只保留type值，形成简单数组
    $firm = array_column($firm, 'name');

    return json_encode($firm, JSON_UNESCAPED_UNICODE);
    }

    public function addnav()
    {
        $data = input('post.');
        $res = Db::name('fa_elevator_components_info')->insert($data);
        if ($res) {
            return '添加成功';
        }else{
            return '添加失败';
        }
         
        // return json_encode($data,JSON_UNESCAPED_UNICODE);
        // $this->success('返回成功', $this->request->param());
    }
    // 生成二维码
    public function build($code)
    {
        $config = get_addon_config('qrcode');
        if (isset($config['limitreferer']) && $config['limitreferer']) {
            $referer = $this->request->server('HTTP_REFERER', '');
            $refererInfo = parse_url($referer);
            $refererHost = $referer && $refererInfo ? $refererInfo['host'] : '';
            $refererHostArr = explode('.', $refererHost);
            $wildcardDomain = '';
            if (count($refererHostArr) > 2) {
                $refererHostArr[0] = '*';
                $wildcardDomain = implode('.', $refererHostArr);
            }
            $allowRefererList = $config['allowrefererlist'] ?? '';
            $domainArr = explode("\n", str_replace("\r", "", $allowRefererList));
            $domainArr = array_filter(array_unique($domainArr));
            $domainArr[] = request()->host(true);

            $inAllowList = false;

            if (in_array('*', $domainArr) || ($refererHost && in_array($refererHost, $domainArr)) || ($wildcardDomain && in_array($wildcardDomain, $domainArr))) {
                $inAllowList = true;
            }

            if (!$inAllowList && (!$referer && $config['allowemptyreferer'])) {
                $inAllowList = true;
            }

            if (!$inAllowList) {
                $response = Response::create('暂无权限', 'html', 403);
                throw new HttpResponseException($response);
            }
        }
        $params = $this->request->get();
        $params = array_intersect_key($params, array_flip(['text', 'size', 'padding', 'errorlevel', 'foreground', 'background', 'logo', 'logosize', 'logopath', 'label', 'labelfontsize', 'labelalignment']));
        //原有$config['text'] 为二维码码值，通过配置获取
        // $params['text'] = $this->request->get('text', $config['text'], 'trim');
        $params['text'] = $this->request->get('text', $code, 'trim');
        $params['label'] = $this->request->get('label', $config['label'], 'trim');

        $qrCode = \addons\qrcode\library\Service::qrcode($params);

        $mimetype = $config['format'] == 'png' ? 'image/png' : 'image/svg+xml';

        $response = Response::create()->header("Content-Type", $mimetype);

        // // 直接显示二维码
        // header('Content-Type: ' . $qrCode->getContentType());
        // $response->content($qrCode->writeString());

        // 写入到文件
        // var_dump($config['writefile']);die();
        if ($config['writefile']) {
            $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
            if (!is_dir($qrcodePath)) {
                @mkdir($qrcodePath);
            }
            if (is_really_writable($qrcodePath)) {
                $filePath = $qrcodePath . md5(implode('', $params)) . '.' . $config['format'];
                $qrCode->writeFile($filePath);
                $qrcodevalue = substr($filePath, strpos($filePath, "uploads") - 1);
            }
        }

        return $qrcodevalue;
    }
}
